<?php
/*
Content Manager for Google Form Links. To be used by students during lectures upon directions from the teacher. The survey links
are sorted by teachers and courses to make the browsing convenient. Teachers can sign in using their Gmail to edit courses and surveys. Only valid gmails may sign in, and the admin makes the decision on what gmails are valid.

@author Mikael Åsberg 2011-05-15
*/

 /*
 User Settings -- START
 db_host: the address to a host with a mysql database
 db_name: name of a database that this server will use
 db_user: username to login to the database
 db_pass: password to login to the database
 path: the path to the surveysite directory
 admin: google email for the admin, this gmail will be used to sign in to the admins account
 */
	$db_host = "surveys-111654.mysql.binero.se";
	$db_name = "111654-surveys";
	$db_user = "111654_zr53377";
	$db_pass = "password";
	$path = "";
	$admin = "mikael.asberg89@gmail.com";
	
 /*
 User Settings -- END
 */
 
 
session_start();

   if ($_GET["login"] != null){
	   
	  		include 'login.php';
		   $googleLogin = GoogleOpenID::createRequest($path."/surveysite/?signed=true", null, true); 
		   $googleLogin->redirect(); 	
		   		
   }else if ($_GET["back"] != null){
	   
	   if ($_SESSION['hIndex'] > 1){
	  	 $_SESSION['hIndex'] = $_SESSION['hIndex'] - 2;
		 
		 $history = $_SESSION['history'];
		 $index = $_SESSION['hIndex'];
		  header("Location: ".$history[$index]);
	
	   }
   }else{
   
			   if ($_SESSION['hIndex'] == null){
					  
				  $history[0] = getAddress();
				  $_SESSION['history'] = $history;
				  $_SESSION['hIndex'] = 1;
			   }else{
				   $history = $_SESSION['history'];
				   $index = $_SESSION['hIndex'];
				   $history[$index] = getAddress();
				   $_SESSION['hIndex'] = $index + 1;
				   $_SESSION['history'] = $history;
				   
			   }
   }
?> 


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Uppsala University Surveys</title>
</head>

<body>
<?php
	$edit_user_html = "<table border='0'>
					<tr><td><b>Update information.</b> Empty fields are ignored. </td></tr>
					<tr><td>
					<table border='0'>
					
					<form name='input' action='' method='get'>
					<tr><td>First name: </td><td><input type='text' name='firstName'  /></td></tr>
					<tr><td>Last name: </td><td><input type='text' name='lastName' /></td></tr>
					<tr><td>UU-code: </td><td><input type='text' name='code'  /></td></tr>
					<input type='hidden' name='editUser' value = 'true'  />
					<tr><td><input type='submit' value='Submit' /></td></tr>
					</form></table></td></tr></table> ";
	//Connect to the DB
	$con = mysql_connect($db_host,$db_user,$db_pass);
	if (!$con)
	  {
		  die('Could not connect: ' . mysql_error());
		  //echo "Access not granted.";
	  }else{
		 //echo "Access granted."; 
	  }

	// Select DB
	
	if (mysql_select_db($db_name, $con)){
		//echo "DB selected";	
	}else{
		 //echo "DB not selected." .  mysql_error();	
	};	  

	$sql_Persons = "CREATE TABLE Persons 
	(
	personID int NOT NULL AUTO_INCREMENT,
	PRIMARY KEY(personID),
	firstName varchar(50),
	lastName varchar(50),
	code varchar(15),
	email varchar(50),
	googleID varchar(200),
	admin boolean
	)";
	if (mysql_query($sql_Persons,$con) ){
		$sql_Courses = "CREATE TABLE Courses 
		(
		courseID int NOT NULL AUTO_INCREMENT,
		courseName varchar(100),
		courseCode varchar(15),
		period varchar(10),
		year int,
		PRIMARY KEY (courseID)
		)";
		$sql_HasCourses = "CREATE TABLE HasCourses 
		(
		personID int,
		courseID int,
		CONSTRAINT pk PRIMARY KEY (personID,courseID),
		FOREIGN KEY (personID) REFERENCES Persons(personID),
		FOREIGN KEY (courseID) REFERENCES Courses(courseID)
		)";
		$sql_Surveys = "CREATE TABLE Surveys 
		(
		surveyID int NOT NULL AUTO_INCREMENT,
		PRIMARY KEY(surveyID),
		name varchar(30),
		link varchar(200),
		courseID int,
		date DATE,
		lectureID int,
		FOREIGN KEY (courseID) REFERENCES Courses(courseID)
		)";
		
		// Execute query
		if (mysql_query($sql_Courses,$con )  && mysql_query($sql_Surveys,$con) && mysql_query($sql_HasCourses,$con) 
		    && mysql_query("INSERT INTO Persons (email, admin) VALUES('".$admin."', true)",$con)){
			echo "System successfully installed.";	
		}else{
			 echo "Error installing system." .  mysql_error();	
		};	  		
	};	  


	  
	  if ($_GET["logout"] != null){
	  		logout();
	  }

	   displayMenu(); //show menu  


	  
	  //check for get tags

	  if ($_GET["editUser"] != null){ //user submitted user info
		    editUser();
	  }	else  if ($_GET["editCourse"] != null){ //user submitted course info
		    editCourse();
	  }else if ($_GET["get"] == "course"){ //check for get tags
		    displayCourses($_GET["personID"]);
	  }else if ($_GET["get"] == "survey"){
	  		displaySurveys($_GET["courseID"]);
	  }else if ($_GET["editToolsUser"] != null){
	  		displayEditToolsUser();
	  }else if ($_GET["editSurvey"] != null){
	  		editSurvey();
	  }else if ($_GET["showSurvey"] != null){
	  		showSurvey();
	  }else if ($_GET["editValidUserTools"] != null){
	  		displayValidUserTools();
	  }else if ($_GET["editValidUser"] != null){
	  		editValidUsers();
	  }else{ //no tags set -> main page, which means list teachers
		  displayTeachers();
	  }
  

/*show a survey with surveyID from $_GET["showSurvey"]*/
function showSurvey(){
	 $id = $_GET["showSurvey"];
	 $row =  mysql_fetch_array(mysql_query("SELECT * FROM Surveys WHERE SurveyID = '$id'"));
	  echo "<iframe src='".$row['link']. "' width='615' height='1010' frameborder='0' marginheight='0' marginwidth='0'>Läser 					in...</iframe>";
}
/*display a list of surveys belonging to course with courseID $courseID*/
 function displaySurveys($courseID)
 {
	$result = mysql_query("SELECT * FROM Surveys WHERE courseID = '$courseID'");
    $teacherID = $_GET["teacherID"];
	$course_info =  mysql_fetch_array(mysql_query("SELECT * FROM Courses WHERE courseID = '$courseID'"));
	
	echo "<table border='1'><tr>";
	
	echo "<th>Surveys for course: ".$course_info['courseName']." ".$course_info['courseCode']." ".$course_info['year'];
	echo	" ". $course_info['period'] . "</th></tr>";
	if(isset($_SESSION['user']) && $teacherID == $_SESSION['user']){
		//$teacher_info =  mysql_fetch_array(mysql_query("SELECT * FROM Persons WHERE personID = $teacherID"));
		if ($teacherID == $_SESSION['user']){
		echo "<form name='input' action='' method='get'>";
		
		while($row = mysql_fetch_array($result))
		{
			  echo "<tr>";
			  echo "<td>" . "<a href=?showSurvey=". $row['surveyID'] . ">";
			  echo "Lecture ". $row['lectureID'] .  ": " . $row['name'] . " " . $row['date'] . "</a>";
			  echo "<input type='radio' name='surveyID' value='". $row['surveyID']."'/></td>";
			  echo "</tr>";
		}
		   echo "<tr><td>Default <input type='radio' name='surveyID' value = '". $row['surveyID']."'/></td></tr>";
		  echo "</table>";
			echo "<table border='0'><tr>";
			echo "<th>Add or Edit a Survey</th></tr>";		  
		   echo "<tr><td>Survey Name</td><td><input type='text' name='surveyName' </></td></tr>";
		   echo "<tr><td>Link</td><td><input type='text' name='link' </></td></tr>";
		   echo "<tr><td>Lecture ID</td><td><input type='text' name='lectureID' </></td></tr>";
		   echo "<tr><td>Date (yyyy-mm-dd) </td><td><input type='text' name='date' </></td></tr>";
		   echo "<input type='hidden' name='courseID' value = '".$courseID."'</>";
		   echo "<input type='hidden' name='teacherID' value = '".$teacherID."'</>";
		   echo "<input type='hidden' name='editSurvey' value = 'true'</>";
		   echo  "<tr><td><input type='checkbox' name='delete' value = 'delete' /> Delete selected Survey</td></tr>";
		   echo "<tr><td><input type='submit' value='Update' /></td></tr>";
		   echo "</table>";
		  echo "</form> ";
		  
		}
	}else{	
		while($row = mysql_fetch_array($result))
		  {
		  echo "<tr>";
		   echo "<td>" . "<a href=?showSurvey=". $row['surveyID'] . ">";
		  echo "Lecture ". $row['lectureID'] .  ": " . $row['name'] . " " . $row['date'] . "</a></td>";
		  echo "</tr>";
		  }
		echo "</table>";
	}
	
 }
/*display a list of courses belonging to teacher with $teacherID*/
 function displayCourses($teacherID)
 {
	$result = mysql_query("SELECT * FROM HasCourses AS a, Courses AS b
							WHERE a.personID = $teacherID
							AND   a.courseID = b.courseID");
							
	$teacher_info = mysql_fetch_array(mysql_query("SELECT * FROM Persons WHERE personID = '$teacherID'"));
	echo "<table border='1'><tr>";
	echo "<th>Courses held by: ".$teacher_info['firstName']. " ".$teacher_info['lastName']."</th></tr>";
	
	if(isset($_SESSION['user']) && $teacherID == $_SESSION['user']){
		echo "<form name='input' action='' method='get'>";
		
		while($row = mysql_fetch_array($result))
		  { 
		  
		  echo "<tr>";
		  echo "<td><a href=?get=survey&courseID=" . $row['courseID']."&teacherID=".$teacherID.">";
		  echo $row['courseName'] . " " . $row['courseCode'] . " ". $row['year'] . " " . $row['period'] ."</a>";
		  echo "<input type='radio' name='courseID' value='". $row['courseID']."'/></td>";
		  echo "</tr>";
		  }
		  echo "<tr><td>Default <input type='radio' name='courseID' value = '". $row['courseID']."'/></td></tr>";
		  echo "</table>";
			echo "<table border='0'><tr>";
			echo "<th>Modify a Course</th></tr>";		  
		   		  
		   echo "<tr><td>Course Name</td><td><input type='text' name='courseName' </></td></tr>";
		   echo "<tr><td>Course Code</td><td><input type='text' name='courseCode' </></td></tr>";
		   echo "<tr><td>Period </td><td><select name='period'>
	  			<option value='' ></option>
				<option value='1' >1</option>
				<option value='2'>2</option>
				<option value='3' >3</option>
				<option value='4'>4</option>
				</select></td></tr>";
		   echo "<tr><td>Year </td><td><input type='text' name='year' </></td></tr>";
		   echo "<input type='hidden' name='personID' value = '".$teacherID."'</>";
		   echo "<input type='hidden' name='editCourse' value = 'true'</>";
		   echo  "<tr><td><input type='checkbox' name='delete' value = 'delete' /> Delete selected Course<br /></td></tr>";
		   echo "<tr><td><input type='submit' value='Update' /></td></tr>";
		  echo "</form></table> ";
	}else{
		while($row = mysql_fetch_array($result))
		  { 
		  echo "<tr>";
		  echo "<td><a href=?get=survey&courseID=" . $row['courseID']."&teacherID=".$teacherID.">";
		  echo $row['courseName'] . " " . $row['courseCode'] . " ". $row['year'] . " " . $row['period'] . "</a></td>";
		  echo "</tr>";
		  }		
		  echo "</table>";
	}
	
	
 }
/*display a list of all teachers*/
 function displayTeachers()
 {
	 $result = mysql_query("SELECT * FROM Persons");
	echo "<table border='1'>
	<tr>
	<th>Teachers</th>
	</tr>";

		
	while($row = mysql_fetch_array($result) )
	  {
		  if ($row['firstName'] != null){
				$mark_start = "";
				$mark_end = "";		  
				if(isset($_SESSION['user']) && $row['personID'] == $_SESSION['user']){
					$mark_start = "<b>";
					$mark_end = "</b>";
				} 		  
			  echo "<tr>";
			  echo "<td>"."<a href=?get=course";
			  echo "&personID=" . $row['personID'] . ">" .$mark_start.$row['firstName']." ".$row['lastName'].$mark_end."</td></tr>";
		  }
	  }
	
	echo "</table>";
 } 

/**
 validate a login attempt. Validation is passed if the Google ID was already in the Persons database, which happens when
 a user has signed in before. If the user has not signed in, the Google mail has to be validated. Only the admin decides
 what Google mails are valid. 
 */
 function validateUser()
 {
	if(isset($_SESSION['googleid'])){
	    $userID = $_SESSION['googleid'];
		$userEmail =	$_SESSION['email'];
		$result = mysql_query("SELECT * FROM Persons WHERE googleID = '$userID'");
		$row = mysql_fetch_array($result);
		global $edit_user_html;
		if (!$row){ //new user
			 $valid = mysql_fetch_array(mysql_query("SELECT * FROM Persons WHERE email = '$userEmail'"));
			 if ($valid){ //email is valid
				 echo "New user. Please fill in information.";
				 $result = mysql_query("UPDATE Persons SET googleID='$userID' WHERE email = '$userEmail'");
				 $row = mysql_fetch_array(mysql_query("SELECT personID FROM Persons WHERE googleID = '$userID'"));			
				 $_SESSION['user'] = $row['personID'];										  
				 echo $edit_user_html;	
			 }else{
			   echo "Email not valid. Ask admin to add your email.";	 
			 }
		}else{
			//echo "Welcome " . $row['firstName'] . $row['lastName'];	
			  $_SESSION['user'] = $row['personID'];		
		}
	} 

 }

 /*convert a link to Google Form from viewform to embedded form*/
  function formatLink($link){
 	 $google = strpos($link, 'https://spreadsheets.google.com');
	 $viewform = strpos($link, 'viewform');
	 if ($google !== false && $viewform !== false){ //google forms in viewform, convert to embedded form
			 $new_link = str_replace('viewform', 'embeddedform', $link);   	 		 
			 return  $new_link;	 	  			   
	 }else{ 
			return  $link;			 
	 }
}
  /**
 edit a survey. Can edit an existing survey or add a new one.
 */
 function editSurvey()
 {
	if(isset($_SESSION['user'])){
		
	    $userID = $_SESSION['user'];
		$courseID = $_GET["courseID"];
		$surveyName = $_GET["surveyName"];
		$link = $_GET["link"];
		$date = $_GET["date"];
		$lectureID = $_GET["lectureID"];
		$surveyID = $_GET["surveyID"];
		
		
		
		if ($surveyID){
		    if ($_GET["delete"]){ //delete box checked
			    //DELETE FROM HASCOURSES INSTEAD. 
				$result = mysql_query("DELETE FROM Surveys WHERE surveyID = '$surveyID'");
				if (!$result ){
					 echo "error delete." . mysql_error();
				}else if ($result && mysql_affected_rows() == 1){
					echo "Deleted existing info.";
				}						   	
			}else{			
				$result = mysql_query("SELECT * FROM Surveys WHERE surveyID = '$surveyID'");		
				$row = mysql_fetch_array($result);
								if (!$row){
									 echo "survey not found.";
								}else{
									 $surveyName = $surveyName == null ? $row['name'] : $surveyName;
									 $link = $link == null ? $row['link'] : formatLink($link);
									 $date = $date == null ? $row['date'] : $date;	
									 $lectureID = $lectureID == null ? $row['lectureID'] : $lectureID;	
								}					
								
				$result = mysql_query("UPDATE Surveys SET name ='$surveyName',link = '$link',date = '$date',lectureID = 								   										'$lectureID' WHERE surveyID = '$surveyID'");
				
				if (!$result ){
					 echo "error update." . mysql_error();
				}else if ($result && mysql_affected_rows() == 1){
					echo "Updated existing info.";
				}	
			}
		}else{			
		    if ($_GET["delete"]){ //delete box checked
					 echo "No survey selected to delete!";
						   	
			}else{			
			    $link = formatLink($link);			
				$result = mysql_query("SELECT * FROM Surveys WHERE
				name = '$surveyName' AND link = '$link'");
				
				if (!$result) {
				   echo "Failed to add survey." . mysql_error();	
				};
				
				if (mysql_affected_rows() == 0){			
					$result = mysql_query("INSERT INTO Surveys (name, link, date, lectureID, courseID)
									VALUES ('$surveyName','$link','$date', '$lectureID', '$courseID')");
					if (!$result){
						 echo "Failed to add survey." . mysql_error();
					}else{
						echo "Added new survey.";
					}
				}
			}
		}
	} 
	
	displaySurveys($courseID);

 }
 
 
 /**
 edit user information.
 */

 function editUser()
 {	 
	if(isset($_SESSION['user'])){
		
	    $userID = $_SESSION['user'];
		$fname = $_GET["firstName"];
		$lname = $_GET["lastName"];
		$code = $_GET["code"];

		$result = mysql_query("SELECT * FROM Persons WHERE personID = '$userID'");	
		$row = mysql_fetch_array($result);
						if (!$row){
							 echo "person not found.";
						}else{
							 $fname = $fname == null ? $row['firstName'] : $fname;
							 $lname = $lname == null ? $row['lastName'] : $lname;
							 $code = $code == null ? $row['code'] : $code;	
						}					
						
		$result = mysql_query("UPDATE Persons SET firstName = '$fname', lastName = '$lname', code = '$code'
								WHERE personID = '$userID'");
		
		if (!$result){
			 echo "Failed to update user info." . mysql_error();
		}else{
			echo "Updated user info.";
		}
	} 
	
	displayTeachers();

 }
 
 /**
display tools to edit user information
 */

 function displayEditToolsUser()
 {
	if(isset($_SESSION['user'])){
	    $userID = $_SESSION['user'];
		$result = mysql_query("SELECT * FROM Persons WHERE personID = '$userID'");
		$row = mysql_fetch_array($result);
		global $edit_user_html;
		if (!$row){
			echo "Current user not found in database. Please sign in.</br>";
			 
		}else{		
			
			 echo "  <table border='0'>
			 		<tr><th>Your personal information</td></tr>
					<tr><td>
			        <table border='0'>
					<tr><td>Firstname</td><td>".$row['firstName']."</td></tr>
					<tr><td>Lastname</td><td>".$row['lastName']. "</td></tr>
					<tr><td>UU-code</td><td>".$row['code']. "</td></tr>
					</table></td></tr>";			 
			 echo $edit_user_html;	
		}
	} 
 } 
  /**
 edit course information. Can edit an existing course or add a new course.
 */

 function editCourse()
 {
	if(isset($_SESSION['user'])){
		
	    $userID = $_SESSION['user'];
		$courseName = $_GET["courseName"];
		$courseCode = $_GET["courseCode"];
		$period = $_GET["period"];
		$courseID = $_GET["courseID"];
		$year = $_GET["year"];
		$teacherID = $_GET["personID"];
		
		if ($courseID){ //course exists 
		    if ($_GET["delete"]){ //delete box checked
			    //DELETE FROM HASCOURSES INSTEAD. 
				$result = mysql_query("DELETE FROM HasCourses WHERE courseID = '$courseID' AND personID = '$teacherID'");
				if ($result && mysql_affected_rows() == 1){
					echo "Deleted existing info.";
				}	
				$result = mysql_query("SELECT * FROM HasCourses WHERE courseID = '$courseID'");
				$row = mysql_fetch_array($result);
				if (!$row){
					 mysql_query("DELETE FROM Courses WHERE courseID = '$courseID'");
				}						   	
			}else{  //update existing course with input fields that actually recieved input
					$result = mysql_query("SELECT * FROM Courses WHERE courseID = '$courseID'");	
						$row = mysql_fetch_array($result);
						if (!$row){
							 echo "course not found.";
						}else{
							 $courseName = $courseName == null ? $row['courseName'] : $courseName;
							  $courseCode = $courseCode == null ? $row['courseCode'] : $courseCode;
							   $period = $period == null ? $row['period'] : $period;
								$year = $year == null ? $row['year'] : $year;	
						}					
								$result = mysql_query("UPDATE Courses 
								SET courseName = '$courseName', courseCode = '$courseCode', period = '$period', year = '$year'
								WHERE courseID = '$courseID'");
					
						if (!$result){
							 echo "Failed to update existing course." . mysql_error();
						}else{
							echo "Updated existing info.";
						}
					}
		}else{ //course may exist but created by other teachers
		    if ($_GET["delete"]){ //delete box checked, by mistake
					echo "No course selected to delete!<br>";	
			}else{
	
					//Find out if course already exists				
					$result = mysql_query("SELECT courseID FROM Courses WHERE courseName = '$courseName' AND courseCode = 			                                                       '$courseCode' AND period = '$period' AND year = '$year'");
					if (!$result){
						 echo "retrieve id error." . mysql_error();
					}										
					$row = mysql_fetch_array($result);
					if (!$row){ //Course doesnt exists, so insert it.
						 //insert into year ("") results in year = 0. But can keep it, so something is displayed.
						$result = mysql_query("INSERT INTO Courses (courseName, courseCode, period, year)
										VALUES ('$courseName', '$courseCode', '$period', '$year')");
													
							if (!$result){
								 echo "add course error." . mysql_error();
							}		
						//Find the new id and insert into HasCourses
						$result = mysql_query("SELECT courseID FROM Courses WHERE courseName = '$courseName' AND courseCode = 			                                                       '$courseCode' AND period = '$period' AND year = '$year'");	
						$row = mysql_fetch_array($result);	
						$newID = $row['courseID'];
						$result = mysql_query("INSERT INTO HasCourses (personID, courseID)
									VALUES ('$teacherID', '$newID')");							
						if (!$result){
							 echo "Failed to add new course." . mysql_error();
						}else{
							echo "Added new course.";
						}											
												 
					}else{
						$newID = $row['courseID'];
						$result = mysql_query("INSERT INTO HasCourses (personID, courseID)
									VALUES ('$teacherID', '$newID')");							
						if ($result && mysql_affected_rows() == 1){
							echo "Added an existing course.";
						}							
					}							
			}
			
		}
		displayCourses($teacherID);

	} 
	
	

 }
  /**
 logout current user
 */
 function logout()
 {
	if(isset($_SESSION['user'])){
	    session_destroy();
		unset($_SESSION['user']);
		unset($_SESSION['googleid']); 
		unset($_SESSION['history']);
		unset($_SESSION['hIndex']);
	}
 }
 /**
 display menu */
 function displayMenu()
 {  
	 if ($_GET["signed"] == "true"){
		   include "login.php";
			 $googleResponse = GoogleOpenID::getResponse();
			  if($googleResponse->success()){
				$_SESSION['googleid'] = $googleResponse->identity();
				$_SESSION['email'] = $googleResponse->email();
			  }	   
	    validateUser();	 
	 }
	if(isset($_SESSION['user'])){
	    $userID = $_SESSION['user'];
		$result = mysql_query("SELECT * FROM Persons WHERE personID = '$userID'");
		$row = mysql_fetch_array($result);
		echo "<table border='0'>";
		if ($row){
		//	echo "<tr><td>You are currently signed in " . $row['firstName'] . $row['lastName']."</td></tr>";				
		}
		echo "<tr><td>You are currently signed in.";
		echo "<tr><td><table border='0'><tr><td>
			 <form action='' >
			 <input type='hidden' name='back' value='true' />
			 <input type='submit' value='<<'>	
			  </form></td><td> 		
			 <form action='' >
			  <input type='hidden' name='home' value='true' />
			 <input type='submit' value='Home'>	
			 </form></td><td>
			   <form action=''>	
			  <input type='hidden' name='editToolsUser' value='true' />
			 <input type='submit' value='Edit User'>
			 </form></td><td>";	
		echo "<form action='' >
			  <input type='hidden' name='logout' value='true' />
			 <input type='submit' value='Logout'>
			  </form></td><td>";
		if ($row['admin'] == true){	 
			echo "<form action=''>
				  <input type='hidden' name='editValidUserTools' value='true' />
				 <input type='submit' value='Edit Accounts'>				 
				 </form></td></tr></table>";
		}
		
		echo " 	</td></tr></table>";				 
			 		
	} else{
		global $login_page;
		echo "<table border='0'><tr><td>
			 <form action='' >
			 <input type='hidden' name='back' value='true' />
			 <input type='submit' value='<<'>	
			  </form></td><td> 		
			 <form action='' >
			  <input type='hidden' name='home' value='true' />
			 <input type='submit' value='Home'>	
			  </form></td><td>
		     <form action=''>
			 <input type='hidden' name='login' value='true' />
			 <input type='submit' value='Login'>
			 </form>
			 </td></tr></table>";		

	} 

	  
 }

/*display tools to edit emails that are granted access to login to the site*/
 function displayValidUserTools()
 {
	 $result = mysql_query("SELECT * FROM Persons");
	echo "<table border='1'>
	<tr>
	<th>Accounts</th>
	</tr><form name='input' action=''>";

		
	while($row = mysql_fetch_array($result))
	  {
	  echo "<tr>";
	  echo "<td>" . $row['email'] ."<input type='radio' name='existEmail' value='".  $row['email'] ."'/></td></tr>";
	  }
	
	echo "</table>";
	echo "<table border='0'>
					<tr><td>Add or delete an account. </td></tr>
					<tr><td>
					<table border='0'>
					
					
					<tr><td>Email of new account: </td><td><input type='text' name='email'  /></td></tr>
					<input type='hidden' name='editValidUser' value = 'true'  />
					<tr><td><input type='checkbox' name='delete' value = 'delete' /> Delete selected account</td></tr>
					<tr><td><input type='submit' value='Submit' /></td></tr>
					
					</form></table></td></tr></table> ";	
 }
 /*edit an email that should be granted access to the site*/
  function editValidUsers()
 {
		if(!isset($_SESSION['user'])){
			echo "No authorization.";
			return;
		}
		$email= $_GET["existEmail"];
		$newEmail = $_GET["email"];
		if (isset($_GET["delete"])){
				if(!$email){
				 		echo "No email selected to delete.";
				}else{
					$result = mysql_query("DELETE FROM Persons WHERE email = '$email'"); 	
						if (!$result){
							 echo "failed to delete.";
						}else{
							echo "Deleted account."; 
						}
				  }			
	   	
		}else{
				if(!$newEmail){
				 		echo "E-Mail is not valid";
				}else{
				  if (!filter_var($newEmail, FILTER_VALIDATE_EMAIL)){
					     echo "E-Mail is not valid";
				  }else{
									$result = mysql_query("INSERT INTO Persons (email) VALUES ('$newEmail')"); 
									if (!$result){
										 echo "failed to add account.";
									}else{
										  echo "succeeded to add account.";
									}	
				  }	
				}
		}
		
	
	
	displayValidUserTools();

 }
  
/**
 *
 * @get the full url of page
 *
 * @return string
 *
 */
 function getAddress()
 {
    /*** check for https ***/
    $protocol = $_SERVER['HTTPS'] == 'on' ? 'https' : 'http';
    /*** return the host address ***/
    return $protocol.'://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
 }
 
 //close the db connection
mysql_close($con);


?> 
</body>
</html>